package hu.monitor.remoting.transport.socket;

import hu.monitor.remoting.transport.ConnectException;
import hu.monitor.remoting.transport.Marshaller;
import hu.monitor.remoting.transport.MarshallerClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;

public class SocketClient extends MarshallerClient {
	private final Socket socket;
	private final SocketAddress endpoint;

	public SocketClient(final Marshaller marshaller, final SocketAddress endpoint) {
		super(marshaller);
		this.endpoint = endpoint;
		this.socket = new Socket();
	}

	@Override
	public void connect() throws IOException {
		try {
			this.socket.connect(this.endpoint);
		} catch (final java.net.ConnectException ex) {
			final String msg = String.format("Error connecting to "+this.endpoint);
			throw new ConnectException(msg, ex);
		}
	}

	@Override
	public void close() throws IOException {
		if (this.socket.isConnected()) {
			this.socket.close();
		}
	}

	@Override
	protected InputStream getInputStream() throws IOException {
		return this.socket.getInputStream();
	}

	@Override
	protected OutputStream getOutputStream() throws IOException {
		return this.socket.getOutputStream();
	}

	@Override
	protected void closeInputStream(final InputStream input) throws IOException {
	}

	@Override
	protected void closeOutputStream(final OutputStream output) throws IOException {
	}

}
